﻿
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using Nui.Utility.Windows;
using Chat;
using System.Collections.ObjectModel;


namespace NiteWpfDemo
{
	public partial class MainWindow : Window
	{
        bool isLoggedIn = false;

		public MainWindow()
		{
			m_session = new NuiSession();
            m_session.PropertyChanged += new PropertyChangedEventHandler(m_session_PropertyChanged);

            m_session.SwipeLeft += new EventHandler(m_session_SwipeLeft);
            m_session.SwipeRight += new EventHandler(m_session_SwipeRight);
            m_session.SwipeUp += new EventHandler(m_session_SwipeUp);
            m_session.SwipeDown += new EventHandler(m_session_SwipeDown);
            m_session.PointChanged += new EventHandler(m_session_PointChanged);
            m_session.Push += new EventHandler(m_session_Push);

			DataContext = m_session;

			InitializeComponent();

            initAndSignInToChat();

			CompositionTarget.Rendering += CompositionTarget_Rendering;




		}

        void m_session_Push(object sender, EventArgs e)
        {
            _client.SendChat("action,push");
        }

        //===============
        //===============
        //===============
        //tweak the tollerance for messages sent in x milliseconds
        //===============
        //===============
        //===============
        DateTime lastSent = DateTime.Now;
        int millisecondsBetweenPosts = 100;


        void m_session_PointChanged(object sender, EventArgs e)
        {

            if (DateTime.Now.Subtract(lastSent).TotalMilliseconds < millisecondsBetweenPosts) return;
            lastSent = DateTime.Now;

            
            try
            {
                _client.SendChat("mouse," + Math.Round(m_session.Point.Value.X, 0) + "," + Math.Round(m_session.Point.Value.Y, 0));
            }
            catch (Exception ex) { 
            
            
            }
        }

        void m_session_SwipeDown(object sender, EventArgs e)
        {
            _client.SendChat("action,down");
        }

        void m_session_SwipeUp(object sender, EventArgs e)
        {
            _client.SendChat("action,up");
        }

        void m_session_SwipeRight(object sender, EventArgs e)
        {
            _client.SendChat("action,right");
        }

        void m_session_SwipeLeft(object sender, EventArgs e)
        {
            _client.SendChat("action,left");
        }

        void m_session_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName.ToLower() == "state")
            {
                if (isLoggedIn)
                {
                    _client.SendChat("state," + ((NuiSession)sender).State.ToString().ToLower());
                }

                //((NuiSession)sender).State


            }
        }

		protected override void OnClosing(CancelEventArgs e)
		{
			if (m_session != null)
			{
				m_session.Dispose();
				m_session = null;
			}
		}

		private void CompositionTarget_Rendering(object sender, EventArgs e)
		{
			ImageOutput.Source = m_session.GetColorImage();
			DepthOutput.Source = m_session.GetDepthImage();
		}

		NuiSession m_session;












        protected Client _client = null;


        private void initAndSignInToChat()
        {
            int serverPort = 4520;
            //int.TryParse(port.Text, out serverPort);

            _client = new Client("localhost", serverPort, "kinect");

            _client.SignedIn += new EventHandler<EventArgs>(_client_SignedIn);
            _client.SignInFailed += new EventHandler<ClientEventArgs>(_client_SignInFailed);
            _client.SignedOut += new EventHandler<EventArgs>(_client_SignedOut);
            _client.ChatReceived += new EventHandler<MessageEventArgs>(_client_ChatReceived);
            _client.UserJoined += new EventHandler<MessageEventArgs>(_client_UserJoined);
            _client.UserLeft += new EventHandler<MessageEventArgs>(_client_UserLeft);
            _client.UserList += new EventHandler<MessageEventArgs>(_client_UserList);
            _client.SystemEvent += new EventHandler<ClientEventArgs>(_client_SystemEvent);
            _client.SignIn();
        }


        void _client_SignInFailed(object sender, ClientEventArgs e)
        {
            this.Dispatcher.BeginInvoke((Action)delegate
            {
                MessageBox.Show("Sign-in failed: " + e.Text);
                
            });
        }

        void _client_UserList(object sender, MessageEventArgs e)
        {
            this.Dispatcher.BeginInvoke((Action)delegate
            {
                ObservableCollection<string> users = new ObservableCollection<string>();
                foreach (string user in e.Message.Data)
                    users.Add(user);

                
            }, null);
        }



        void _client_SystemEvent(object sender, ClientEventArgs e)
        {
            //addText(e.Time, "System Event: " + e.Text);
        }

        void _client_UserJoined(object sender, MessageEventArgs e)
        {
            //string newUser = e.Message.Data[0];

            //addText(e.Message.Time, "User '" + newUser + "' joined the chat.");

            //this.Dispatcher.BeginInvoke((Action)delegate
            //{
            //    ObservableCollection<string> userNames = chatUsers.ItemsSource as ObservableCollection<string>;
            //    if (userNames != null)
            //    {
            //        if (!userNames.Contains(newUser))
            //            userNames.Add(newUser);
            //    }
            //});
        }

        void _client_UserLeft(object sender, MessageEventArgs e)
        {
            //string newUser = e.Message.Data[0];

            //addText(e.Message.Time, "User '" + newUser + "' left the chat.");

            //this.Dispatcher.BeginInvoke((Action)delegate
            //{
            //    ObservableCollection<string> userNames = chatUsers.ItemsSource as ObservableCollection<string>;
            //    if (userNames != null)
            //    {
            //        if (userNames.Contains(newUser))
            //            userNames.Remove(newUser);
            //    }
            //});
        }

        void _client_ChatReceived(object sender, MessageEventArgs e)
        {
            //addText(e.Message.Time, e.Message.Data[0] + ": " + e.Message.Data[1]);
        }

        void _client_SignedIn(object sender, EventArgs e)
        {
            isLoggedIn = true;

            this.Dispatcher.BeginInvoke((Action)delegate
            {
                //output.Text = String.Empty;
                //input.Text = string.Empty;
                //sendButton.IsEnabled = false;

                //gridSignedIn.Visibility = Visibility.Visible;
                //gridSignIn.Visibility = Visibility.Collapsed;
            });
        }

        void _client_SignedOut(object sender, EventArgs e)
        {
            this.Dispatcher.BeginInvoke((Action)delegate
            {
                //gridSignedIn.Visibility = Visibility.Collapsed;
                //gridSignIn.Visibility = Visibility.Visible;

                //signInButton.IsEnabled = true;
            });
        }

        void _client_ClientEvent(object sender, ClientEventArgs e)
        {
            //addText(e.Time, e.Text);
        }
	}
}
